<template>
  <div class="model-title">{{ title }}</div>
  <div class="cesium-container" ref="cesiumContainer" id="cesiumContainer"></div>
  <div />
</template>

<script setup>
import { onMounted, onUnmounted, ref } from 'vue'
import { getFileQX, getModelByTaskId } from '@/api/model.js'
import * as Cesium from 'cesium'
import { useRoute } from 'vue-router'

// 容器引用
const cesiumContainer = ref(null);
const { proxy } = getCurrentInstance();
const route = useRoute();
const title = ref('')

// 组件挂载时初始化
onMounted(() => {
  getData();
});

// 获取数据
const getData = async () => {
  try {
    proxy.$modal.loading('正在加载模型，请稍候...');
    // 获取数据详情
    const res = await getModelByTaskId(route.query.id);
    title.value = res.data.name;
    const path = JSON.parse(res.data.previewFileName)?.json.find(i => i.indexOf('tileset.json') > -1);
    // 获取下载链接
    await getFileQX(path.split('/')[0]);
    await initCesium(path);
    proxy.$modal.closeLoading();
  } catch (error) {
    proxy.$modal.closeLoading();
  }
}
// 初始化Cesium
const initCesium = async (path) => {
  try {
    // 配置Cesium Token
    Cesium.Ion.defaultAccessToken = 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJqdGkiOiI3ZjQ5ZGUzNC1jNWYwLTQ1ZTMtYmNjYS05YTY4ZTVmN2I2MDkiLCJpZCI6MTE3MTM4LCJpYXQiOjE2NzY0NDUyODB9.ZaNSBIfc1sGLhQd_xqhiSsc0yr8oS0wt1hAo9gbke6M';

    // 创建viewer实例
    window.viewer = new Cesium.Viewer(cesiumContainer.value, {
      terrainProvider: undefined,
      imageryProvider: false, // 禁用默认影像图层
      baseLayerPicker: false,
      geocoder: false,
      homeButton: false,
      sceneModePicker: false,
      navigationHelpButton: false,
      animation: false,
      timeline: false,
      fullscreenButton: false,
      vrButton: false,
      infoBox: false,
      selectionIndicator: false,
      scene3DOnly: true,
    })
    // 修改鼠标控制设置
    const controller = viewer.scene.screenSpaceCameraController;
    /**
     * 启用鼠标控制
     * enableRotate: 允许旋转
     * enableTranslate: 允许平移
     * enableZoom: 允许缩放
     * enableTilt: 允许倾斜
     * enableLook: 允许视角调整
     */
    controller.enableRotate = true;
    controller.enableTranslate = true;
    controller.enableZoom = true;
    controller.enableTilt = true;
    controller.enableLook = true;
    /**
     * 鼠标控制方式设置：
     * LEFT_DRAG: 左键拖动 - 用于旋转模型
     * RIGHT_DRAG: 右键拖动 - 用于调整视角倾斜度
     * WHEEL: 滚轮 - 用于缩放
     */
    controller.rotateEventTypes = Cesium.CameraEventType.LEFT_DRAG;  // 左键旋转模型
    controller.tiltEventTypes = Cesium.CameraEventType.RIGHT_DRAG;   // 右键调整倾斜角度

    /**
     * 设置滚轮缩放
     * WHEEL: 鼠标滚轮
     * PINCH: 触摸屏双指缩放
     */
    controller.zoomEventTypes = [
      Cesium.CameraEventType.WHEEL,
      Cesium.CameraEventType.PINCH
    ];

    // 禁用浏览器默认的右键菜单，以便使用右键进行视角控制
    document.getElementById('cesiumContainer').addEventListener('contextmenu', (e) => {
      e.preventDefault();
    });

    // 移除默认的天空盒和大气效果
    viewer.scene.skyBox.destroy()
    viewer.scene.skyBox = undefined
    viewer.scene.sun.destroy()
    viewer.scene.sun = undefined
    viewer.scene.moon.destroy()
    viewer.scene.moon = undefined
    viewer.scene.skyAtmosphere.destroy()
    viewer.scene.skyAtmosphere = undefined
    viewer.scene.backgroundColor = new Cesium.Color(0.5, 0.5, 0.5, 1.0) // 设置为灰色背景

    // 基础性能优化
    viewer.scene.globe.enableLighting = false
    viewer.scene.globe.show = false // 隐藏地球
    viewer.scene.fog.enabled = false

    // **加载 3D Tiles**
    const tileset = await Cesium.Cesium3DTileset.fromUrl("/3d-model/" + path, {
      skipLevelOfDetail: true,
      baseScreenSpaceError: 1024,
      skipScreenSpaceErrorFactor: 16,
      skipLevels: 1,
      immediatelyLoadDesiredLevelOfDetail: false,
      loadSiblings: false,
      cullWithChildrenBounds: true
    });
    // 添加到场景
    viewer.scene.primitives.add(tileset);
    // 定位到模型
    await viewer.zoomTo(tileset);
    // 设置相机位置
    const boundingSphere = tileset.boundingSphere
    const center = boundingSphere.center
    const radius = boundingSphere.radius
    //设置相机位置
    viewer.camera.position = new Cesium.Cartesian3(
      center.x + radius * -0.5,
      center.y + radius * 1,
      center.z + radius * -1
    )
    viewer.camera.direction = Cesium.Cartesian3.normalize(
      Cesium.Cartesian3.subtract(center, viewer.camera.position, new Cesium.Cartesian3()),
      new Cesium.Cartesian3()
    )

    // 添加基础光照
    const lightDirection = new Cesium.Cartesian3(-1.0, -1.0, -1.0)
    Cesium.Cartesian3.normalize(lightDirection, lightDirection)
    viewer.scene.light = new Cesium.DirectionalLight({
      direction: lightDirection,
      intensity: 2.0,
      color: new Cesium.Color(1.0, 1.0, 1.0)
    })
  } catch (error) {
    proxy.$modal.msgError('加载模型失败', error);
    console.error('Failed to initialize Cesium:', error);
  }
}

// 组件卸载时清理资源
onUnmounted(() => {
  if (viewer) {
    viewer.destroy()
    viewer = null
  }
})
</script>

<style scoped lang="scss">
.model-title {
  position: absolute;
  top: 12px;
  left: 12px;
  color: #fff;
  font-size: 18px;
  z-index: 99;
}

.cesium-container {
  width: 100%;
  height: 100vh;
  position: relative;
  background-color: #808080;
}

/* 优化Cesium的CSS性能 */
:deep(.cesium-widget-credits) {
  display: none !important;
}

:deep(.cesium-widget canvas) {
  image-rendering: optimizeSpeed;
  image-rendering: -webkit-optimize-contrast;
}

:deep(.cesium-viewer-toolbar) {
  display: none;
}

:deep(.cesium-viewer-bottom) {
  display: none;
}

.loading {
  width: 100%;
  height: 100%;
  display: flex;
  align-items: center;
  justify-content: center;
  background-color: rgba(0, 0, 0, .5);

  ::v-deep .el-progress__text {
    color: #fff;
    display: flex;
    flex-direction: column;

    .percentage-value {
      font-size: 16px;
    }

    .percentage-label {
      font-size: 14px;
      margin-top: 12px;
    }
  }
}
</style>
